<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use app\common\facade\admin\AdminAdmin;
use app\common\facade\model\AdminModel;
use app\common\facade\extend\RedisExtend;
use think\facade\Request;
use think\facade\Cache;

class Home extends BaseAdmin
{
    /**
     * 登录
     */
    public function login($param = [])
    {

        $param['enable'] = 2;

        $infoAdmin = AdminAdmin::adminInfo($param);
        
        if (empty($infoAdmin)) exception('账号不存在，或已关闭');
    
        if ((!$infoAdmin || !password_verify($param['password'], $infoAdmin['password']))) exception('帐号或者密码不正确');

        self::checkRule($infoAdmin);

        // 执行用户登陆日志管理
        AdminAdmin::syslog('sys','用户['.$infoAdmin['username'].']-['.$infoAdmin['truename'].']登陆后台！',$infoAdmin);
        
        return self::baseLogin($infoAdmin);
    }

    /**
     * 检查权限
     */
    public function checkRule($param = [])
    {

        if ($param['roleId'] != 0):

            $paramRole = [
                'roleId' => $param['roleId'],
                'enable' => 2,
            ];
            
            $roleInfo = AdminAdmin::roleInfo($paramRole);
            
            if (empty($roleInfo)) exception('抱歉，没有权限访问');

            $paramRule = [
                'path_url' => self::pathRole(),
                'enable' => 2,
            ];

            // 设置公共允许通过权限检查的接口
            $publicMenuItem = [
                'Home/Login',  // 登录接口
                'Home/LoginOut' // 退出登录
            ];

            return true; // 权限控制暂时交给前端处理，默认前端请求的后端接口都允许通过; 

            // if(in_array($paramRule['path_url'],$publicMenuItem)) {
            //     return true;
            // }

            // $ruleInfo = AdminAdmin::ruleInfo($paramRule);
            
            // if (empty($ruleInfo) || !in_array($ruleInfo['id'], $roleInfo['ruleId'])) exception('没有权限访问.');
            
        endif;

        return true;
    }

    /**
     * 检查登录
     */
    public function checkLogin()
    {

        $adminLoginInfo = self::adminLoginInfo();

        // 管理员用户直接跳过权限检查
        if($adminLoginInfo['id'] == '1' && $adminLoginInfo['username'] == 'admin') {
            return true;
        }else{
            self::checkRule($adminLoginInfo);
        }

        return true;
    }

    /**
     * 获取token用户信息
     */
    public function authInfo() {
        $accessLoginHeader = self::accessLoginHeader();
        
        $paramAdmin = [
            'enable'      => 2,
            'access_login' => $accessLoginHeader,
        ];

        $infoAdmin = AdminAdmin::adminInfo($paramAdmin);

        return $infoAdmin;
    }

    /**
     * 处理登录逻辑
     */
    public function baseLogin($param = [], $accessLogin = '')
    {

        if (empty($accessLogin)):
            $accessLogin = hash('sha512', 'admin' . json_encode($param) . time() . random_int(1000, 9999));
            // RedisExtend::del(self::domainBindAdmin() . $param['access_login']);
            Cache::delete(self::domainBindAdmin() . $param['access_login']);

            $dataSaveAdmin['access_login'] = $accessLogin;
        endif;

        $whereSaveAdmin[] = ['id', '=', $param['id']];

        $ip = Request::ip();

        $dataSaveAdmin['login_ip'] = $ip;

        $dataHMSet = [
            'id'      => $param['id'],
            'username' => $param['username'],
            'login_ip' => $ip,
            'roleId'   => $param['roleId']
        ];

        // RedisExtend::hMSet(self::domainBindAdmin() . $accessLogin, $dataHMSet, ['expire' => 7200]);
        Cache::set(self::domainBindAdmin() . $accessLogin, $dataHMSet, 10);

        AdminModel::addEditSave($dataSaveAdmin, $whereSaveAdmin);

        return [
            'token' => $accessLogin,
            'userid'=> $param['id'],
            'user'  => $param
        ];
    }

    /**
     * 退出登录
     */
    public function loginOut()
    {

        $adminLoginInfo = self::adminLoginInfo();

        if (!empty($adminLoginInfo['id'])):

            // 执行用户退出日志管理
            AdminAdmin::syslog('sys','用户['.$adminLoginInfo['username'].'] 退出后台！',$adminLoginInfo);

            Cache::delete(self::domainBindAdmin() . self::accessLoginHeader());


            $where[] = ['id', '=', $adminLoginInfo['id']];

            AdminModel::addEditSave(['access_login' => null], $where);
        endif;

        return true;
    }
}


?>